package com.godfeer.admin.modular.file.controller;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpMethodName;
import com.godfeer.core.base.controller.BaseController;
import com.godfeer.admin.modular.file.service.IVideoService;
import com.godfeer.admin.modular.system.model.Video;
import com.godfeer.admin.myconfig.myenum.FileEnum;
import com.godfeer.admin.myconfig.properties.COSVideoProperties;
import com.godfeer.admin.myconfig.properties.RestTemplateProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * 视频上传控制器
 */
@Api(value = "文件操作")
@RestController
public class VideoUploadController extends BaseController {


    @Autowired
    private IVideoService videoService;

    @Autowired
    private COSVideoProperties cosVideoProperties;

    @Autowired
    private COSClient cosClient;

    @Autowired
    private RestTemplate restTemplate;//rpc调用

    @Autowired
    private RestTemplateProperties restTemplateProperties;

    @ApiOperation(value = "视频上传测试",notes = "/videoUpload")
    @RequestMapping(value = "/videoUpload",method = RequestMethod.POST)
    public Object uploadFile(@ApiParam(required = true)MultipartFile fileVideo,MultipartFile fileImage,
                             Video video) throws IOException {
        Video restVideo = new Video();




        //文件判空
        if(fileVideo == null || fileImage == null){
            log.warn("empty ！");
            return getErrorTip(FileEnum.EMPTY.getMessage(),"");
        }
        String videoOriginalFilename = fileVideo.getOriginalFilename();//视频文件名
        String imageOriginalFilename = fileImage.getOriginalFilename();//图片文件名

        String VIDEO_PATH = cosVideoProperties.getVideoPath();
        String IMAGE_PATH = cosVideoProperties.getImagePath();
        //判断视频是mp4格式
        String videoSuffix = videoOriginalFilename.split("\\.")[1];
        if(!"mp4".equals(videoSuffix)){
            log.error("video type is wrong !");
            return getErrorTip("请选择视频类型为mp4格式的",videoOriginalFilename);
        }
        //判断图片是jpg格式
        String imageSuffix = imageOriginalFilename.split("\\.")[1];
        if(!"png".equals(imageSuffix) && !"jpg".equals(imageSuffix)){
            log.error("image type is wrong !");
            return getErrorTip("请选择图片类型为jpg格式的",imageOriginalFilename);
        }
//********************************************************************************************************
        if(video != null ){
            //视频应该上传的文件夹
           if(video.getVideoType() != null){
               Integer videoType = video.getVideoType();
               if(videoType > 0 && videoType < 4){
                   restVideo.setVideoType(videoType);//设置视频的类型
                   log.info("set image type .");
                   switch(videoType){
                        case 1:
                            VIDEO_PATH += "2d/";
                            break;
                        case 2:
                            VIDEO_PATH += "3d/";
                            break;
                        case 3:
                            VIDEO_PATH += "vr/";
                            break;
                    }
               }else{
                   return getErrorTip("请输入视频类型1--3","");
               }
           }
           //图片应该上传的文件夹
           if(video.getVideoClass() != null){
               Integer getVideoClass = video.getVideoClass();
               if(getVideoClass > 0 && getVideoClass < 5){
                   restVideo.setVideoClass(getVideoClass);//设置视频的分类
                   switch(getVideoClass){
                        case 1:
                            IMAGE_PATH += "part/";
                            break;
                        case 2:
                            IMAGE_PATH += "job/";
                            break;
                        case 3:
                            IMAGE_PATH += "high/";
                            break;
                        case 4:
                            IMAGE_PATH += "k12/";
                            break;
                    }
               }else{
                   return getErrorTip("请输入视频类别1--4","");
               }
           }
           //设置简介
           if(video.getVideoIntroduce() != null && video.getVideoIntroduce() != ""){
               restVideo.setVideoIntroduce(video.getVideoIntroduce());
           }else{
               restVideo.setVideoIntroduce("...");
           }
        }
        //设置视频文件的一些信息
        String preffix = UUID.randomUUID().toString().replaceAll("-", "") + "-";
        String videoCosName = videoOriginalFilename;
        restVideo.setTitle(videoCosName);//设置视频文件名

        //创建临时文件
        final File tempFile = File.createTempFile(preffix,videoOriginalFilename);
        try{
            //写入临时文件
            fileVideo.transferTo(tempFile);
        }catch(IOException e){
            return getErrorTip(FileEnum.DEFAULT.getMessage(),"");
        }
        //发送到云服务器
        URL videoUrl = null;
        try{
            cosClient.putObject(cosVideoProperties.getBucket(), VIDEO_PATH + videoCosName, tempFile);
            Date expiration = new Date(new Date().getTime() + 365 * 24 * 60 * 60 * 1000);//时间365天
            videoUrl = cosClient.generatePresignedUrl(cosVideoProperties.getBucket(),VIDEO_PATH + videoCosName,expiration,HttpMethodName.GET);
            restVideo.setVideoUrl(videoUrl.toString());//设置视频下载路径
        }catch(CosServiceException e){
            return getErrorTip(FileEnum.DEFAULT.getMessage(),"");
        }catch(CosClientException e){
            return getErrorTip(FileEnum.DEFAULT.getMessage(),"");
        }


        //设置图片文件的一些信息
        preffix = UUID.randomUUID().toString().replaceAll("-", "") + "-";
        String imageCosName = imageOriginalFilename;
        restVideo.setImgTitle(imageCosName);//设置图片对应的缩略图名
        //创建临时文件
        final File tempImageFile = File.createTempFile(preffix,imageOriginalFilename);
        try{
            //写入临时文件
            fileImage.transferTo(tempFile);
        }catch(IOException e){
            return getErrorTip(FileEnum.DEFAULT.getMessage(),"");
        }
        //发送到云服务器
        URL imageUrl = null;
        try{
            cosClient.putObject(cosVideoProperties.getBucket(), IMAGE_PATH + imageCosName, tempFile);
            Date expiration = new Date(new Date().getTime() + 365 * 24 * 60 * 60 * 1000);//时间365天
            imageUrl = cosClient.generatePresignedUrl(cosVideoProperties.getBucket(),IMAGE_PATH + imageCosName,expiration,HttpMethodName.GET);
            restVideo.setImgUrl(imageUrl.toString());//设置图片路径
        }catch(CosServiceException e){
            return getErrorTip(FileEnum.DEFAULT.getMessage(),"");
        }catch(CosClientException e){
            return getErrorTip(FileEnum.DEFAULT.getMessage(),"");
        }

        //rpc插入数据库
        Object result = null;
        try{
            result = restTemplate.postForObject(restTemplateProperties.getUrl()+"file/video/rest/upload",restVideo,Object.class);
        }catch(Exception e){
            //插入rest数据库时将插入本地数据库
            boolean count = videoService.insert(restVideo);
            return getErrorTip("插入前端数据库失败，已将记录插入到后台数据库",restVideo);
        }
        return getSuccessTip(FileEnum.SUCCESS.getMessage(),"");
    }

}
